const xmlreader = require('xmlreader');
// const rp = require('request-promise');
const md5 = require('md5');

module.exports = class extends think.Service {
  getmoney(money) {
    return parseFloat(money) * 100;
  }

  // 随机字符串产生函数
  createNonceStr() {
    return Math.random().toString(36).substr(2, 15);
  }

  // 时间戳产生函数
  createTimeStamp() {
    return parseInt(new Date().getTime() / 1000) + '';
  }

  // 签名加密算法
  paysignjsapi(appid, openid, body, mchId, nonceStr, notifyUrl, outTradeNo, spbillCreateIp, totalFee, tradeType, mchkey) {
    var ret = {
      appid: appid,
      mch_id: mchId,
      nonce_str: nonceStr,
      body: body,
      notify_url: notifyUrl,
      out_trade_no: outTradeNo,
      spbill_create_ip: spbillCreateIp,
      total_fee: totalFee,
      trade_type: tradeType,
      openid: openid
    };
    console.log('ret==', ret);
    var string = this.raw(ret);
    var key = mchkey;
    string = string + '&key=' + key;
    console.log('string=', string);
    var crypto = require('crypto');
    return crypto.createHash('md5').update(string, 'utf8').digest('hex').toUpperCase();
  }
  // 签名加密算法,第二次的签名
  paysignjsapifinal(appid, mchId, prepayid, noncestr, timestamp, mchkey) {
    var ret = {
      appid: appid,
      partnerid: mchId,
      prepayid: prepayid,
      package: 'Sign=WXPay',
      noncestr: noncestr,
      timestamp: timestamp
    };
    console.log('retretret==', ret);
    var string = this.raw(ret);
    var key = mchkey;
    string = string + '&key=' + key;
    console.log('stringstringstring=', string);
    var crypto = require('crypto');
    return crypto.createHash('md5').update(string, 'utf8').digest('hex').toUpperCase();
  }
  getXMLNodeValue(xml) {
    // var tmp = xml.split("<"+node_name+">");
    // console.log('tmp',tmp);
    // var _tmp = tmp[1].split("</"+node_name+">");
    // console.log('_tmp',_tmp);
    // return _tmp[0];
    xmlreader.read(xml, function(errors, response) {
      if (errors !== null) {
        console.log(errors);
        return;
      }
      console.log('长度===', response.xml.prepay_id.text().length);
      var prepayId = response.xml.prepay_id.text();
      console.log('解析后的prepay_id==', prepayId);
      return prepayId;
    });
  }
  raw(args) {
    var keys = Object.keys(args);
    keys = keys.sort();
    var newArgs = {};
    keys.forEach(function(key) {
      newArgs[key] = args[key];
    });
    var string = '';
    for (var k in newArgs) {
      string += '&' + k + '=' + newArgs[k];
    }
    string = string.substr(1);
    return string;
  }
  createUnifiedOrder(payInfo) {
    const WeiXinPay = require('weixinpay');
    const weixinpay = new WeiXinPay({
      appid: think.config('wechat.AppID'), // 微信小程序appid
      openid: payInfo.openid, // 用户openid
      mch_id: think.config('wechat.mch_id'), // 商户帐号ID
      partner_key: think.config('wechat.partner_key') // 秘钥
    });
    return new Promise((resolve, reject) => {
      weixinpay.createUnifiedOrder({
        body: payInfo.body,
        out_trade_no: payInfo.out_trade_no,
        total_fee: payInfo.total_fee,
        spbill_create_ip: payInfo.spbill_create_ip,
        notify_url: think.config('wechat.paymentNotifyUrl'),
        trade_type: 'JSAPI'
      }, (res) => {
        if (res.return_code === 'SUCCESS' && res.result_code === 'SUCCESS') {
          const returnParams = {
            'appid': res.appid,
            'timeStamp': parseInt(Date.now() / 1000) + '',
            'nonceStr': res.nonce_str,
            'package': 'prepay_id=' + res.prepay_id,
            'signType': 'MD5'
          };
          const paramStr = `appId=${returnParams.appid}&nonceStr=${returnParams.nonceStr}&package=${returnParams.package}&signType=${returnParams.signType}&timeStamp=${returnParams.timeStamp}&key=` + think.config('wechat.partner_key');
          returnParams.sign = md5(paramStr).toUpperCase();
          resolve(returnParams);
        } else {
          reject(res);
        }
      });
    });
  }
  createUnifiedVip(payInfo) {
    const WeiXinPay = require('weixinpay');
    const weixinpay = new WeiXinPay({
      appid: think.config('wechat.AppID'), // 微信小程序appid
      openid: payInfo.openid, // 用户openid
      mch_id: think.config('wechat.mch_id'), // 商户帐号ID
      partner_key: think.config('wechat.partner_key') // 秘钥
    });
    return new Promise((resolve, reject) => {
      weixinpay.createUnifiedOrder({
        body: payInfo.body,
        out_trade_no: payInfo.out_trade_no,
        total_fee: payInfo.total_fee,
        spbill_create_ip: payInfo.spbill_create_ip,
        notify_url: think.config('wechat.vipNotifyUrl'),
        trade_type: 'JSAPI'
      }, (res) => {
        if (res.return_code === 'SUCCESS' && res.result_code === 'SUCCESS') {
          const returnParams = {
            'appid': res.appid,
            'timeStamp': parseInt(Date.now() / 1000) + '',
            'nonceStr': res.nonce_str,
            'package': 'prepay_id=' + res.prepay_id,
            'signType': 'MD5'
          };
          const paramStr = `appId=${returnParams.appid}&nonceStr=${returnParams.nonceStr}&package=${returnParams.package}&signType=${returnParams.signType}&timeStamp=${returnParams.timeStamp}&key=` + think.config('wechat.partner_key');
          returnParams.sign = md5(paramStr).toUpperCase();
          resolve(returnParams);
        } else {
          reject(res);
        }
      });
    });
  }
};
